#include "SimpleLight.h"

const char* SimpleLight::beginMsg_ = ("{\"cmd\":\"light\", \"id\":\"");
const char* SimpleLight::stateOn_ = ("\", \"state\":\"on\"}");
const char* SimpleLight::stateOff_ = ("\", \"state\":\"off\"}");

void SimpleLight::publishCircuitState(){
	if(circuitState_)
		postMessage( String(beginMsg_) + lightCircuit_ + stateOn_);
	else
		postMessage( String(beginMsg_) + lightCircuit_ + stateOff_);
}
SimpleLight::SimpleLight(IArduino& arduino, MessageRouter& router, const String& name, ILogger& logger, const String& buttonName, const String& lightCircuit): 
Service(arduino, router, name, logger), buttonName_(allocateString(buttonName)), lightCircuit_(allocateString(lightCircuit)), circuitState_(false), state_(READY){
}
SimpleLight::~SimpleLight(){
	free(buttonName_);
	free(lightCircuit_);
}

void SimpleLight::tick(long milliseconds) {
}
bool SimpleLight::onItem(const String& name, const String& value){
	switch(state_){
			  case READY:
				  if(name == F("event") && value == F("button")){
					  state_ = BUTTON_EVENT;
					  return true;
				  }
				  break;
			  case BUTTON_EVENT:
				  if(name == F("id") && value == buttonName_){
					  return true;
				  }
				  if(name == F("state") && value == F("on")){
					  circuitState_=!circuitState_;
					  publishCircuitState();
					  state_ = READY;
					  return false;
				  }
				  break;
	}
	state_ = READY;
	return false;
}

